const fs = require("fs");
const uuid = require('node-uuid');

const qiNiu = require("qiniu");
const config = require('./../config');
const { ACCESS_KEY , SECRET_KEY } = config.qiNiu;

qiNiu.conf.ACCESS_KEY = ACCESS_KEY;
qiNiu.conf.SECRET_KEY = SECRET_KEY;


const uploadQiNiu = ( suffix , filePath ) => {

    const fileName = `${uuid.v1()}${suffix}`;

    const bucket = `yutao`; //上传空间名

    const upToken = ()=> {
        const putPolicy = new qiNiu.rs.PutPolicy(`${bucket}:${fileName}`);
        return putPolicy.token();
    };

    return new Promise(( resolve , reject ) => {
        const token = upToken();
        const extra = new qiNiu.io.PutExtra();
        qiNiu.io.putFile(token,fileName,filePath,extra,(err,ret) => {
            if(!!err) {
                reject(`上传失败！`);
            }
            else {
                resolve(`${config.staticUrl}${ret.key}`);
            }
            fs.unlinkSync(filePath);
        });
    });
};

const isImage = type => {
    const test=()=>{
        switch (type) {
            case `image/pjpeg`: return `jpg`;
            case `image/jpeg`: return `jpg`;
            case `image/png`: return `png`;
            case `image/x-png`: return `png`;
            case `image/gif`:return `gif`;
            default:return false;
        }
    };
    return !!test();
};

const getFileSuffix = fileName => {
    const result= /\.[^\.]+$/.exec(fileName);
    return result[0];
};

exports.getFileSuffix = getFileSuffix;
exports.uploadQiNiu = uploadQiNiu;
exports.isImage = isImage;